<template>
  <el-scrollbar height="calc(100vh - 50px)">
  <div class="dashboard">
    <!-- Stats Cards Row -->
    <el-row :gutter="12" class="mb-30">
      <el-col v-for="(item, index) in proInfo" :key="index" 
              :xs="24" :sm="12" :md="8" :lg="6" :xl="3" 
              class="mb-18">
        <el-card shadow="hover" class="stat-card hover-scale" v-loading="loading">
          <div class="card-header">
            <div class="stat-title">{{item.name}}</div>
            <countTo
                class="stat-value"
                :start-val="0"
                :end-val="item.count"
                :duration="2600">
            </countTo>
          </div>
          <div v-if="item.changeType==='lastIncrease'" class="stat-change">
            <span>自上周增长</span>
            <span class="percentage increase-icon"><el-icon><Top /></el-icon>{{item.percentage}}</span>
          </div>
          <div v-if="item.changeType==='lastDecrease'" class="stat-change">
            <span>自上周下降</span>
            <span class="percentage decrease-icon"><el-icon><Bottom /></el-icon>{{item.percentage}}</span>
          </div>
          <div v-if="item.changeType==='yastdayIncrease'" class="stat-change">
            <span>自昨日增长</span>
            <span class="percentage increase-icon"><el-icon><Top /></el-icon>{{item.percentage}}</span>
          </div>
          <div v-if="item.changeType==='yastdayDecrease'" class="stat-change">
            <span>自昨日下降</span>
            <span class="percentage decrease-icon"><el-icon><Bottom /></el-icon>{{item.percentage}}</span>
          </div>
          <div v-if="item.changeType==='job'" class="job-status">
            <span>运行中：<b>{{item.run_service}}</b></span>
            <span class="paused-status">已暂停：<b>{{item.paused}}</b></span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Charts Row -->
    <el-row :gutter="18" class="mb-20">
        <el-col :xs="24" :sm="24" :md="12" :lg="9" class="mb-18" v-if="proCase && proCase.length > 0">
          <el-card shadow="hover" class="chart-card" v-loading="loading">
            <template #header>
              <div class="card-header-flex">
                <div class="header-title">
                  <strong>近七日接口维护统计</strong>
                  <el-icon><Suitcase /></el-icon>
                </div>
                <div class="date-filter-wrapper">
                  <el-popover
                    placement="bottom"
                    trigger="click"
                    width="auto"
                    popper-class="date-filter-popover"
                  >
                    <template #reference>
                      <el-button type="primary" size="small" class="filter-btn">
                        <el-icon style="margin-right: 5px;"><Calendar /></el-icon>
                         时间筛选
                      </el-button>
                    </template>
                    <div class="date-filter">
                      <el-date-picker
                        v-model="dataTime"
                        type="datetimerange"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        :default-time="defaultTimeOptions"
                        :shortcuts="shortcuts"
                        range-separator="至"
                        :clearable="true"
                        class="date-picker"
                      />
                      <el-button type="primary" @click="submitForm" class="search-btn" :loading="loading">
                        <el-icon><Search /></el-icon>查询
                      </el-button>
                    </div>
                  </el-popover>
                </div>
              </div>
            </template>
            <div class="chart-container">
              <ApiChart :testData="proCase"></ApiChart>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="8" class="mb-18" v-if="buttonClick && buttonClick.length > 0">
          <el-card shadow="hover" class="chart-card" v-loading="loading">
            <template #header>
              <div class="card-header-flex">
                <div class="header-title">
                  <strong>近七日平台使用频率</strong>
                  <el-icon><DataAnalysis /></el-icon>
                </div>
              </div>
            </template>
            <div class="chart-container">
              <WeekLoginChart :testData="buttonClick"></WeekLoginChart>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="7" class="mb-18" v-if="proBug && proBug.length > 0">
          <el-card shadow="hover" class="chart-card" v-loading="loading">
            <template #header>
              <div class="card-header-flex">
                <div class="header-title">
                  <strong>bug处理情况</strong>
                  <el-icon><PieChart /></el-icon>
                </div>
              </div>
            </template>
            <div class="chart-container">
              <BugChart :testData="proBug"></BugChart>
            </div>
          </el-card>
        </el-col>
    </el-row>

    <!-- Bottom Row -->
    <el-row :gutter="18">
        <el-col :xs="24" :sm="24" :md="12" :lg="9" class="mb-18" v-if="mockLog && mockLog.length > 0">
          <el-card shadow="hover" class="log-card" v-loading="loading">
            <template #header>
              <div class="card-header-flex">
                <div class="header-title">
                  <strong>Mock日志</strong>
                  <el-icon><Tickets /></el-icon>
                </div>
              </div>
            </template>
          <div class="timeline-container">
            <el-timeline>
              <el-timeline-item v-for="(activity, index) in mockLog"
                                :key="index"
                                :timestamp="$tools.rTime(activity.create_time)"
                                placement="top"
                                color="#0bbd87">
              <div class="log-item">
                <el-tag v-if="activity.method==='GET'" type="success" size="small">{{activity.method}}</el-tag>
                <el-tag v-else size="small">{{activity.method}}</el-tag>
                <span class="log-url">{{activity.url}}</span>
                <div class="log-details">
                  <span class="log-label">调用IP：</span>
                  <span class="log-value">{{activity.ip}}</span>
                  <span class="log-label">HTTP状态码：</span>
                  <span 
                    class="log-status"
                    :class="{
                      'status-success': activity.status_code==='200',
                      'status-warning': activity.status_code==='400',
                      'status-error': activity.status_code==='500'
                    }">
                    {{activity.status_code}}
                  </span>
                  <span class="log-time">{{activity.time_consuming}}</span>
                </div>
              </div>
              </el-timeline-item>
            </el-timeline>
          </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="15" class="mb-18" v-if="proReport && proReport.length > 0">
          <el-card shadow="hover" class="chart-card" v-loading="loading">
            <template #header>
              <div class="card-header-flex">
                <div class="header-title">
                  <strong>近三天报告运行情况统计</strong>
                  <el-icon><DataAnalysis /></el-icon>
                </div>
                <div class="header-info">
                  <span>通过率(%)</span>
                </div>
              </div>
            </template>
            <div class="chart-container">
              <ReportChart :testData="proReport"></ReportChart>
            </div>
          </el-card>
        </el-col>
    </el-row>
  </div>
  </el-scrollbar>
</template>

<script >
import { ElCard, ElRow, ElCol} from 'element-plus';
import ApiChart from '../../components/echart/ApiChart.vue'
import WeekLoginChart from '../../components/echart/WeekLoginChart.vue'
import BugChart from '../../components/echart/BugChart.vue'
import ReportChart from '../../components/echart/ReportChart.vue'
import {mapMutations, mapState} from 'vuex';
import countTo from '../../components/to'
import { 
  Top, 
  Bottom, 
  Suitcase, 
  Calendar, 
  Search, 
  DataAnalysis, 
  PieChart, 
  Tickets, 
} from '@element-plus/icons-vue'

export default {
  components: {
    ElCard, ElRow, ElCol,
    ApiChart, countTo, WeekLoginChart,
    BugChart, ReportChart,
    Top, Bottom, Suitcase, Calendar, 
    Search, DataAnalysis, PieChart, Tickets
  },
  data() {
    // 创建默认的近七天时间范围
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
    
    // 格式化日期为 "YYYY-MM-DD HH:mm:ss" 格式
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day} ${date.getHours() === 0 ? '00' : date.getHours()}:${date.getMinutes() === 0 ? '00' : date.getMinutes()}:${date.getSeconds() === 0 ? '00' : date.getSeconds()}`
    }
    
    return {
      proall: null,
      proInfo: null,
      proBug:null,
      proCase:null,
      proReport:null,
      buttonClick:null,
      mockLog:null,
      defaultTimeOptions: ['00:00:00', '23:59:59'],
      // 默认设置为近七天的时间范围
      dataTime: [formatDate(start), formatDate(end)],
      shortcuts: [
        {
          text: '过去一周',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
          },
        },
        {
          text: '过去一个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
          },
        },
        {
          text: '过去三个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
          },
        },
      ],
      screenSize: {
        xs: false,
        sm: false,
        md: false,
        lg: false,
        xl: false
      },
      loading: false
    };
  },
 	methods: {
		...mapMutations(['selectPro']),
    async getProInfo(starttime, endtime) {
      this.loading = true;
      try {
        let data = {"project": this.pro.id};
        if(starttime && endtime){
          data = {"project": this.pro.id,"starttime": starttime, "endtime": endtime}
        }
        const response = await this.$api.getProjectBoard(data);
        if (response.status === 200) {
          this.proall = response.data;
          this.proInfo = this.proall.project_info;
          this.proBug = this.proall.project_bug;
          this.proCase = this.proall.project_case;
          this.proReport = this.proall.project_report;
          this.buttonClick = this.proall.track_button_click;
          this.mockLog = this.proall.mock_log;
        }
      } catch (error) {
        console.error('获取项目看板数据失败:', error);
      } finally {
        this.loading = false;
      }
    },
    submitForm() {
      if (!this.dataTime){
        this.dataTime = []
      }
      const starttime = this.dataTime[0]
      const endtime = this.dataTime[1]
      this.getProInfo(starttime, endtime)
    },
    handleResize() {
      const width = window.innerWidth;
      this.screenSize = {
        xs: width < 576,
        sm: width >= 576 && width < 768,
        md: width >= 768 && width < 992,
        lg: width >= 992 && width < 1200,
        xl: width >= 1200
      };
    }
	},
	computed: {
		...mapState(['pro']),
	},
	created() {
    // 使用默认的近七天时间范围获取数据
    const starttime = this.dataTime[0]
    const endtime = this.dataTime[1]
		this.getProInfo(starttime, endtime);
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
	},
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style scoped>
.dashboard {
  padding: 16px;
  background: #f7fafc;
  min-height: calc(100vh - 50px);
}

/* Responsive spacing */
.mb-12 {
  margin-bottom: 12px;
}

.mb-18 {
  margin-bottom: 18px;
}

.mb-20 {
  margin-bottom: 20px;
}


/* Card styling */
.el-card {
  --el-card-border-color: transparent;
  --el-card-border-radius: 12px;
  --el-card-padding: 16px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
  transition: all 0.3s ease;
  border: none;
  overflow: hidden;
  margin-bottom: 10px;
}

.hover-scale:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.09) !important;
}

/* Stats cards */
.stat-card {
  height: 100%;
  background: linear-gradient(135deg, #ffffff 0%, #f9fafb 100%);
  position: relative;
  overflow: hidden;
}

.stat-card::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(90deg, #6366f1 0%, #8b5cf6 50%, #ec4899 100%);
  opacity: 0.7;
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 0.3s ease;
}

.stat-card:hover::after {
  transform: scaleX(1);
}

.card-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 16px;
}

.stat-title {
  font-size: 16px;
  font-weight: 600;
  color: #4b5563;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #111827;
  line-height: 1.2;
}

.stat-change {
  font-size: 14px;
  color: #6b7280;
  margin-top: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.increase-icon {
  display: inline-flex;
  align-items: center;
  color: #10b981;
  font-size: 14px;
  font-weight: 600;
}

.decrease-icon {
  display: inline-flex;
  align-items: center;
  color: #ef4444;
  font-size: 14px;
  font-weight: 600;
}

.percentage {
  margin-left: auto;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
}

.percentage .el-icon {
  margin-right: 4px;
}

.job-status {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  margin-top: 20px;
  color: #6b7280;
}

.job-status b {
  font-weight: 600;
  color: #111827;
  margin-left: 4px;
}

.paused-status {
  color: #ef4444;
}

/* Chart cards */
.chart-card {
  height: 100%;
  background: white;
}

.card-header-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f1f5f9;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.header-title i {
  font-size: 18px;
  color: #6366f1;
}

.date-filter-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.filter-btn {
  background: #6366f1;
  border-color: #6366f1;
  transition: all 0.3s ease;
  font-weight: 500;
}

.filter-btn:hover {
  background: #4f46e5;
  border-color: #4f46e5;
  transform: translateY(-2px);
}

.date-filter-popover {
  padding: 16px !important;
  border-radius: 8px !important;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12) !important;
}

.date-filter {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 320px;
}

.date-picker {
  width: 100%;
}

@media (max-width: 1200px) {
  .date-picker {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .card-header-flex {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .date-filter-wrapper {
    width: 100%;
  }
  
  .date-picker {
    width: 100%;
  }
  
  .search-btn {
    margin-left: 0;
    width: 100%;
  }
}

.search-btn {
  width: 100%;
  background: #6366f1;
  border-color: #6366f1;
  transition: all 0.3s ease;
}

.search-btn:hover {
  background: #4f46e5;
  border-color: #4f46e5;
  transform: translateY(-2px);
}

.chart-container {
  height: calc(100% - 40px);
  padding: 16px;
}

/* Log card */
.log-card {
  height: 100%;
}

.timeline-container {
  height: calc(100% - 52px);
  padding: 8px;
  overflow-y: auto;
}

.log-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: 100%;
}

.log-url {
  margin: 6px 0;
  font-family: monospace;
  color: #4b5563;
  font-size: 13px;
  word-break: break-all;
}

.log-details {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  margin-top: 4px;
}

.log-label {
  font-weight: 600;
  font-size: 13px;
  color: #4b5563;
}

.log-value {
  font-size: 13px;
  color: #6b7280;
}

.log-status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 600;
}

.status-success {
  background-color: #d1fae5;
  color: #059669;
}

.status-warning {
  background-color: #fef3c7;
  color: #d97706;
}

.status-error {
  background-color: #fee2e2;
  color: #dc2626;
}

.log-time {
  font-size: 13px;
  color: #6b7280;
  margin-left: auto;
}

.header-info {
  font-size: 14px;
  color: #6b7280;
}

/* Dark mode compatibility & theme variables */
:root {
  --primary-color: #6366f1;
  --success-color: #10b981;
  --warning-color: #f59e0b;
  --danger-color: #ef4444;
  --text-primary: #111827;
  --text-secondary: #4b5563;
  --text-tertiary: #6b7280;
  --bg-card: #ffffff;
  --bg-page: #f7fafc;
}

@media (prefers-color-scheme: dark) {
  :root {
    --primary-color: #818cf8;
    --success-color: #34d399;
    --warning-color: #fbbf24;
    --danger-color: #f87171;
    --text-primary: #f9fafb;
    --text-secondary: #e5e7eb;
    --text-tertiary: #d1d5db;
    --bg-card: #1f2937;
    --bg-page: #111827;
  }
}

/* 修复popover样式，这需要全局生效 */
:deep(.el-popover.date-filter-popover) {
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}
</style>
